package com.crm.base.config;
import com.crm.base.domain.LoginUser;
import com.crm.base.utils.JWTUtils;
import com.crm.base.domain.User;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class TokenFilter extends OncePerRequestFilter {


    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain filterChain) throws ServletException, IOException {

        if (req.getRequestURI().contains("/user/login")) {
            filterChain.doFilter(req, resp);
            return;
        }

        String token = req.getHeader("X-Token");
        if (StringUtils.hasText(token)) {

//            User user = (User) redisTemplate.opsForValue().get("user:info:" + token);

            User user = JWTUtils.parse(token);

            if (Objects.nonNull(user)) {
                LoginUser loginUser = new LoginUser(user);

                UsernamePasswordAuthenticationToken u = new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());

                SecurityContextHolder.getContext().setAuthentication(u);
            }else {
                LoginUser loginUser = new LoginUser(new User());

                UsernamePasswordAuthenticationToken u = new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());

                SecurityContextHolder.getContext().setAuthentication(u);
            }
        }

        filterChain.doFilter(req, resp);

    }
}
